let core = require('./core.js');
const formatDatetime = function(date, fmt) { //author: meizz
  if(!date) {
    return "";
  }
  if(!(date instanceof Date)) {
    if(/^\d+$/.test(date)) {
      date = (date+"").length>10 ? date : date*1000;
      date = new Date(parseInt(date));
    }else {
      date = new Date(date.replace(/-/g,'/'));
    }
  }
  var o = {
    "m+": date.getMonth() + 1, //月份
    "d+": date.getDate(), //日
    "h+": date.getHours(), //小时
    "i+": date.getMinutes(), //分
    "s+": date.getSeconds(), //秒
    "q+": Math.floor((date.getMonth() + 3) / 3), //季度
    "S": date.getMilliseconds() //毫秒
  };
  var yearMatch = fmt.match(/(y+)/);
  if (yearMatch) {
    fmt = fmt.replace(yearMatch[0], (date.getFullYear() + "").substr(4 - yearMatch[0].length));
  }
  for (var k in o) {
    var match = fmt.match(new RegExp("(" + k + ")"));
    if (match)
      fmt = fmt.replace(match[0], (match[0].length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
  }
  return fmt;
};
/**
 * 加载更多按钮功能
 * page.data定义moreButton(可由moreButtonDataField更改) moreButton.text作为按钮文本, moreButton.page作为页码
 * @param pageInstance
 * @param url 接口地址
 * @param queryData querystring parameters
 * @param moreButtonDataField morebutton data在page.data中的字段名
 * @param listFieldName 渲染的列表数据再page.data中的字段名
 * @param retDataFieldName 接口返回的列表数据再http response ret.data中的字段名
 * @param dataFormatter function, 处理服务器返回的列表数据，返回处理过后的数组, this指向pageInstance
 */
const fetch = function(pageInstance, url,queryData, moreButtonDataField, listFieldName, retDataFieldName, dataFormatter) {
  let moreButtonData = pageInstance[moreButtonDataField] || {page:1};
  if(moreButtonData.loading || moreButtonData.nomore) {
    return;
 }
  queryData.page = moreButtonData.page;
  pageInstance[moreButtonDataField]['loading'] = true;
  pageInstance[moreButtonDataField]['text'] = '正在加载...';
  pageInstance.$forceUpdate();
  core.get({
    url: url, data: queryData,
	loading:false,
    success(ret, response) {
      let listData = retDataFieldName?ret.data[retDataFieldName]:ret.data;
      let listLength = listData.length;
      if(typeof dataFormatter === 'function') {
        //listData = dataFormatter.apply(pageInstance, [listData, ret.data]) || listData;
		dataFormatter(ret.data);
      }else if(dataFormatter==='unique') {
        function uniqueFormatter(listData) {
          let formattedList = [];
          out:  for(let i in listData) {
            let item = listData[i];
            for(let j in pageInstance[listFieldName]) {
              let originItem = pageInstance[listFieldName][j];
              if(originItem.id==item.id) {
                continue out;
              }
            }
            formattedList.push(item);
          }
          return formattedList;
        }
        listData = uniqueFormatter(listData);
      }
      if(Array.isArray(listData) && listLength>0) {
        pageInstance[listFieldName] = (pageInstance[listFieldName] || []).concat(listData);
        let pagesize = queryData.pagesize || 10;
        
        if(listLength<pagesize) {
		  pageInstance[moreButtonDataField]['page'] = moreButtonData.page + 1;
		  pageInstance[moreButtonDataField]['loading'] = false;
		  pageInstance[moreButtonDataField]['nomore'] = true;
		  pageInstance[moreButtonDataField]['text'] = '—— 没有更多了 ——';
        }else {
			
			pageInstance[moreButtonDataField]['page'] = moreButtonData.page + 1;
			pageInstance[moreButtonDataField]['loading'] = false;
			pageInstance[moreButtonDataField]['text'] = '加载更多';
        }
      }else {
        let text = moreButtonData.page == 1 ? '暂无数据' : '—— 没有更多了 ——';
        let nothing = moreButtonData.page == 1 ? true : false;
		pageInstance[moreButtonDataField]['nomore'] = true;
		pageInstance[moreButtonDataField]['text'] = text;
		pageInstance[moreButtonDataField]['nothing'] = nothing;
      }
	  pageInstance.$forceUpdate();
    },
    fail(ret, response) {
		pageInstance[moreButtonDataField]['loading'] = false;
		pageInstance[moreButtonDataField]['text'] = '加载更多';
    }
  })
};
const getRemoteDataCached = async function(options) {
  let data, url = options.url, cacheKey = options.cacheKey, useCache = options.useCache===undefined ? true : options.useCache,
    retDataKey = options.dataKey;
  if(useCache) {
    data = core.getCache(cacheKey);
  }
  if(!data) {
    data = await (new Promise(function(resolve, reject) {
      core.get({
        url: url,
        data: options.data || '',
        loading:false,
        success(ret) {
          resolve(retDataKey ? ret.data[retDataKey]:ret.data);
        },
        fail(ret) {
          reject(ret);
        }
      });
    }));
    core.setCache(cacheKey, data, 1800);
  }
  return data;
};

/**
 * 获取省市区三级树状结构
 * @param {int} level 默认3层
 * @param {boolean} useCache true则先从缓存中获取，否则直接取网络并放入缓存
 * @return {Promise}
 */
const getAreasTree = async function (level=3,useCache=true) {
	let cacheKey = 'areas_tree';
	let areas;
	if(useCache) {
		areas = core.getCache(cacheKey);
	}
	if(!areas) {
		areas = await (new Promise(function(resolve, reject) {
		core.get({
		  url:'/xilujob.common/area_tree',
		  loading:false,
		  success(ret) {
			resolve(ret.data);
		  },
		  fail(ret) {
			reject(ret);
		  }
		});
	  }));
	  core.setCache(cacheKey, areas, 1800);
	}
	if(level==1) {
	  for(let i in areas) {
		delete areas[i].childlist;
	  }
	}else if(level==2) {
	  for(let i in areas) {
		let sendAreas = areas[i].childlist;
		for(let j in sendAreas) {
		  delete sendAreas[j].childlist;
		}
	  }
	}
	return areas;
  };

/**
 * 获取职位分类
 * @param {int} level 默认3层
 * @param {boolean} useCache true则先从缓存中获取，否则直接取网络并放入缓存
 * @return {Promise}
 */
const getJobCategories = async function (level=3,useCache=true) {
  let cacheKey = 'job_categories';
  let categories;
  // if(useCache) {
  //   categories = core.getCache(cacheKey);
  // }
  // if(!categories) {
    categories = await (new Promise(function(resolve, reject) {
      core.get({
        url:'/xilujob.common/job_categories',
        loading:false,
        success(ret) {
          resolve(ret.data);
        },
        fail(ret) {
          reject(ret);
        }
      });
    }));
    core.setCache(cacheKey, categories, 1800);
  // }
  if(level==1) {
    for(let i in categories) {
      delete categories[i].childlist;
    }
  }else if(level==2) {
    for(let i in categories) {
      let sendCategory = categories[i].chilidlist;
      for(let j in sendCategory) {
        delete sendCategory[j].childlist;
      }
    }
  }
  return categories;
};
/**
 * 获得可供选择的福利
 * @param {Boolean} useCache
 * @returns {Promise.<*>}
 */
const getBenefits = async function (useCache=true) {
  let cacheKey = 'benefit_list';
  let benefits;
  if(useCache) {
    benefits = core.getCache(cacheKey);
  }
  if(!benefits) {
    benefits = await (new Promise(function(resolve, reject) {
      core.get({
        url:'/xilujob.common/benefits',
        loading:false,
        success(ret) {
          resolve(ret.data);
        },
        fail(ret) {
          reject(ret);
        }
      });
    }));
    core.setCache(cacheKey, benefits, 1800);
  }
  return benefits;
};
/**
 *	工作经验
 * @param {Boolean} excludeZero 是否排除id<=0的item
 * @param {Boolean} useCache
 * @returns {Promise.<*>}
 */
const getWorkExperienceOptions = async function (excludeZero=false, useCache=true) {
  let cacheKey = 'work_experience_options';
  let options;
  if(useCache) {
    options = core.getCache(cacheKey);
  }
  if(!options) {
    options = await (new Promise(function(resolve, reject) {
      core.get({
        url:'/xilujob.common/work_experience',
        loading:false,
        success(ret) {
          resolve(ret.data);
        },
        fail(ret) {
          reject(ret);
        }
      });
    }));
    core.setCache(cacheKey, options, 1800);
  }
  if(excludeZero) {
    let zeroIdIndex = null;
    for(let i in options) {
      if(options[i].id<=0) {
        zeroIdIndex = i;
        break;
      }
    }
    if(zeroIdIndex!==null) {
      options.splice(zeroIdIndex, 1);
    }
  }
  return options;
};
/**
 * 学历
 * @param {Boolean} excludeZero 是否排除id<=0的item
 * @param {Boolean} useCache
 * @returns {Promise.<*>}
 */
const getEducationLevels = async function (excludeZero=false, useCache=true) {
  let cacheKey = 'education_levels';
  let levels;
  if(useCache) {
    levels = core.getCache(cacheKey);
  }
  if(!levels) {
    levels = await (new Promise(function(resolve, reject) {
      core.get({
        url:'/xilujob.common/education_levels',
        loading:false,
        success(ret) {
          resolve(ret.data);
        },
        fail(ret) {
          reject(ret);
        }
      });
    }));
    core.setCache(cacheKey, levels, 1800);
  }
  if(excludeZero) {
    let zeroIdIndex = null;
    for(let i in levels) {
      if(levels[i].id<=0) {
        zeroIdIndex = i;
        break;
      }
    }
    if(zeroIdIndex!==null) {
      levels.splice(zeroIdIndex, 1);
    }
  }
  return levels;
};

/**
 * 获取薪资区间选项
 * @param {int} salaryType 1时薪,2日薪,3月薪
 * @param {boolean} useCache true则先从缓存中获取，否则直接取网络并放入缓存
 * @return {Promise}
 */
const getSalaryOptions = function (salaryType, useCache=true) {
  let app = getApp();
  let cacheKey = 'salary_options_type_'+salaryType;
  return getRemoteDataCached({
    url: '/xilujob.common/salary/type/' + salaryType,
    cacheKey: cacheKey,
    useCache: useCache,
    dataKey: ''
  });
};
/**
 * 企业类型
 * @param {boolean} useCache true则先从缓存中获取，否则直接取网络并放入缓存
 * @return {Promise}
 */
const getCompanyTypes = function (useCache=true) {
  let cacheKey = 'company_types';
  return getRemoteDataCached({
    url: '/xilujob.common/company_properties',
    cacheKey: cacheKey,
    useCache: useCache,
    dataKey: ''
  });
};

/**
 * 企业规模
 * @param {boolean} useCache true则先从缓存中获取，否则直接取网络并放入缓存
 * @return {Promise}
 */
const getCompanyScales = function (useCache=true) {
  let cacheKey = 'company_scales';
  return getRemoteDataCached({
    url: '/xilujob.common/company_scales',
    cacheKey: cacheKey,
    useCache: useCache,
    dataKey: ''
  });
};
/**
 * 企业行业
 * @param {boolean} useCache true则先从缓存中获取，否则直接取网络并放入缓存
 * @return {Promise}
 */
const getIndustryCategories = function (useCache=true) {
  let cacheKey = 'industry_categories';
  return getRemoteDataCached({
    url: '/xilujob.common/industry_categories',
    cacheKey: cacheKey,
    useCache: useCache,
    dataKey: ''
  });
};
/**
 * 求职状态
 * @param {boolean} useCache true则先从缓存中获取，否则直接取网络并放入缓存
 * @return {Promise}
 */
const getWorkStates = function (useCache=true) {
  let cacheKey = 'work_states';
  return getRemoteDataCached({
    url: '/xilujob.common/work_states',
    cacheKey: cacheKey,
    useCache: useCache,
    dataKey: ''
  });
};
/**
 * 职位举报类型选项
 * @param {boolean} useCache true则先从缓存中获取，否则直接取网络并放入缓存
 * @return {Promise}
 */
const getJobInformTypes = function (useCache=true) {
  let cacheKey = 'job_inform_types';
  return getRemoteDataCached({
    url: '/xilujob.common/job_inform_types',
    cacheKey: cacheKey,
    useCache: useCache,
    dataKey: ''
  });
};
/**
 * 简历个人标签选项
 * @param {boolean} useCache true则先从缓存中获取，否则直接取网络并放入缓存
 * @return {Promise}
 */
const getResumePersonalTags = function (useCache=true) {
  let cacheKey = 'resume_personal_tags';
  return getRemoteDataCached({
    url: '/xilujob.common/resume_personal_tags',
    cacheKey: cacheKey,
    useCache: useCache,
    dataKey: ''
  });
};
/**
 * 获取城市数据，包含省份
 * @param {boolean} useCache true则先从缓存中获取，否则直接取网络并放入缓存
 */
const getCities = function (useCache=true) {
  let cacheKey = 'province_city';
  return getRemoteDataCached({
    url: '/xilujob.common/province_city',
    data: {},
    cacheKey: cacheKey,
    useCache: useCache,
    dataKey: ''
  });
};

/**
 * 获取城市数据
 * @param {boolean} useCache true则先从缓存中获取，否则直接取网络并放入缓存
 */
const getAllCities = function (useCache=true) {
  let cacheKey = 'cities';
  return getRemoteDataCached({
    url: '/xilujob.common/cities',
    data: {},
    cacheKey: cacheKey,
    useCache: useCache,
    dataKey: ''
  });
};

/**
 * 获取区数据，包含下级
 * @param {int} cityId 城市id
 * @param {boolean} useCache true则先从缓存中获取，否则直接取网络并放入缓存
 */
const getAreas = function (cityId='',useCache=true) {
  if(!cityId)
    cityId = core.getCurrentCity().id;
  let cacheKey = 'districts_with_'+cityId;
  return getRemoteDataCached({
    url: '/xilujob.common/districts_with',
    data: {city_id:cityId},
    cacheKey: cacheKey,
    useCache: useCache,
    dataKey: ''
  });
};


/**
 * 评论标签选项
 * @param {boolean} useCache true则先从缓存中获取，否则直接取网络并放入缓存
 * @return {Promise}
 */
const getCommentTags = function (useCache=true) {
  let cacheKey = 'comment_tags';
  return getRemoteDataCached({
    url: '/xilujob.common/comment_tags',
    cacheKey: cacheKey,
    useCache: useCache,
    dataKey: ''
  });
};

/**
 * 就业工种
 * @param {boolean} useCache true则先从缓存中获取，否则直接取网络并放入缓存
 * @return {Promise}
 */
const getTypeWork = function (useCache=true) {
  let cacheKey = 'type_work';
  return getRemoteDataCached({
    url: '/xilujob.common/type_work',
    cacheKey: cacheKey,
    useCache: useCache,
    dataKey: ''
  });
};

/**
 * 自主就业类型
 * @param {boolean} useCache true则先从缓存中获取，否则直接取网络并放入缓存
 * @return {Promise}
 */
const getEmployeeCategory = function (useCache=true) {
  let cacheKey = 'employee_category';
  return getRemoteDataCached({
    url: '/xilujob.common/employee_category',
    cacheKey: cacheKey,
    useCache: useCache,
    dataKey: ''
  });
};

/**
 * 失业原因
 * @param {boolean} useCache true则先从缓存中获取，否则直接取网络并放入缓存
 * @return {Promise}
 */
const getUnemployeeReason = function (useCache=true) {
  let cacheKey = 'unemployee_reason';
  return getRemoteDataCached({
    url: '/xilujob.common/unemployee_reason',
    cacheKey: cacheKey,
    useCache: useCache,
    dataKey: ''
  });
};

/**
 * 培训类型
 * @param {boolean} useCache true则先从缓存中获取，否则直接取网络并放入缓存
 * @return {Promise}
 */
const getTrainCategory = function (useCache=true) {
  let cacheKey = 'train_category';
  return getRemoteDataCached({
    url: '/xilujob.common/train_category',
    cacheKey: cacheKey,
    useCache: useCache,
    dataKey: ''
  });
};

/**
 * 培训专业
 * @param {boolean} useCache true则先从缓存中获取，否则直接取网络并放入缓存
 * @return {Promise}
 */
const getTrainMajor = function (useCache=true) {
  let cacheKey = 'train_major';
  return getRemoteDataCached({
    url: '/xilujob.common/train_major',
    cacheKey: cacheKey,
    useCache: useCache,
    dataKey: ''
  });
};

/**
 * 培训等级
 * @param {boolean} useCache true则先从缓存中获取，否则直接取网络并放入缓存
 * @return {Promise}
 */
const getTrainLevel = function (useCache=true) {
  let cacheKey = 'train_level';
  return getRemoteDataCached({
    url: '/xilujob.common/train_level',
    cacheKey: cacheKey,
    useCache: useCache,
    dataKey: ''
  });
};
/**
 * 零工工种
 * @param {boolean} useCache true则先从缓存中获取，否则直接取网络并放入缓存
 * @return {Promise}
 */
const getTastCategory = function (useCache=true) {
  let cacheKey = 'task_category';
  return getRemoteDataCached({
    url: '/xilujob.common/task_category',
    cacheKey: cacheKey,
    useCache: useCache,
    dataKey: ''
  });
};

/**
 * 工作性质
 * @param {boolean} useCache true则先从缓存中获取，否则直接取网络并放入缓存
 * @return {Promise}
 */
const getTastProperties = function (useCache=true) {
  let cacheKey = 'tast_properties';
  return getRemoteDataCached({
    url: '/xilujob.common/task_properties',
    cacheKey: cacheKey,
    useCache: useCache,
    dataKey: ''
  });
};

/**
 * 实名信息
 * @param {boolean} useCache true则先从缓存中获取，否则直接取网络并放入缓存
 * @return {Promise}
 */
const getUserRealname = function (useCache=false) {
  let cacheKey = 'user_realname';
  return getRemoteDataCached({
    url: '/xilujob.service/user_realname',
    cacheKey: cacheKey,
    useCache: useCache,
    dataKey: ''
  });
};
/**
 * 获取未读消息
 * @param {boolean} useCache true则先从缓存中获取，否则直接取网络并放入缓存
 */
const getMessageCount = function (useCache=true) {
  let cacheKey = 'message_count';
  return getRemoteDataCached({
    url: '/xilutour.message/unread',
    data: {},
    cacheKey: cacheKey,
    useCache: useCache,
    dataKey: ''
  });
};

/**
 * 简历专业技能精通程度选项
 * @param {boolean} useCache true则先从缓存中获取，否则直接取网络并放入缓存
 * @return {Promise}
 */
const getSkillLevels = function (useCache=true) {
  let cacheKey = 'skill_levels';
  return getRemoteDataCached({
    url: '/xilujob.common/skill_levels',
    cacheKey: cacheKey,
    useCache: useCache,
    dataKey: ''
  });
};
const getListItemIndexById = function(list, id) {
  if(!list || !id)
    return -1;
  for(var i=0;i<list.length;i++) {
    if(list[i].id==id) {
      return i;
    }
  }
  return -1;
}
const getListItemById = function(list, id) {
  if(!list || !id)
    return null;
  for(var i=0;i<list.length;i++) {
    if(list[i].id==id) {
      return list[i];
    }
  }
  return null;
}
module.exports = {
	formatDatetime:formatDatetime,
	fetch:fetch,
	getAreasTree: getAreasTree,
	getJobCategories: getJobCategories,
	getBenefits: getBenefits,
	getWorkExperienceOptions: getWorkExperienceOptions,
	getEducationLevels: getEducationLevels,
	getSalaryOptions: getSalaryOptions,
	getCompanyTypes: getCompanyTypes,
	getCompanyScales: getCompanyScales,
	getIndustryCategories:getIndustryCategories,
	getWorkStates: getWorkStates,
	getJobInformTypes: getJobInformTypes,
	getResumePersonalTags: getResumePersonalTags,
	getSkillLevels:getSkillLevels,
	getCities: getCities,
	getAllCities: getAllCities,
	getAreas: getAreas,
	getCommentTags: getCommentTags,
	
	getTypeWork: getTypeWork,
	getEmployeeCategory: getEmployeeCategory,
	getUnemployeeReason: getUnemployeeReason,
	getTrainCategory: getTrainCategory,
	getTrainMajor: getTrainMajor,
	getTrainLevel: getTrainLevel,
	getTastCategory: getTastCategory,
	getTastProperties: getTastProperties,
	getUserRealname: getUserRealname,
	getListItemIndexById:getListItemIndexById,
	getListItemById:getListItemById
};
